<template>
  <a-card>
    <template #title>
      <a-form layout="vertical">
        <a-row :gutter="24">
          <a-col :md="6" :xs="24" v-permiss="['select-merchant']">
            <a-form-item :label="$t('商户名称')">
              <a-select v-model:value="page.mchId" allowClear>
                <a-select-option v-for="item in merchantList" :key="item.mchId" :value="item.mchId">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24" v-permiss="['select-merchant']">
            <a-form-item :label="$t('交易流水')">
              <a-input v-model:value="page.transactionId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('平台订单号')">
              <a-input v-model:value="page.platOrderId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('商户订单号')">
              <a-input v-model:value="page.orderId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('客户姓名')">
              <a-input v-model:value="page.name"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('身份证号码')">
              <a-input v-model:value="page.idCard"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('收款账号')">
              <a-input v-model:value="page.vaNumber"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('标识符')">
              <a-input v-model:value="page.identifier"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('还款类型')">
              <a-select v-model:value="page.transferType" allowClear>
                <a-select-option :value="0">clabe</a-select-option>
                <a-select-option :value="1">OXXO</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('状态')">
              <a-select v-model:value="page.status" allowClear>
                <a-select-option v-for="item in statusList" :key="item.value" :value="item.value">{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('完成时间')">
              <a-range-picker style="width: 100%" v-model:value="page.resolveTime" valueFormat="YYYY-MM-DD"
                              format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <a-button @click="exportExcel" :loading="exportLoading" v-permiss="['export']">{{ $t('导出') }}</a-button>
      <a-button type="primary" style="margin-left: 10px" @click="batchPush" v-permiss="['batch-push']">{{
          $t('批量推送')
        }}
      </a-button>
    </div>
    <a-table row-key="platOrderId" :loading="tableLoading" :data-source="tableData" :columns="tableColumn"
             :row-selection="rowSelection"
             :pagination="pagination" :scroll="{x:true,y:600}">
      <template #handle="{record}">
        <a-button type="link" @click="push(record)" v-permiss="['push']">{{
            $t('推送')
          }}
        </a-button>
      </template>
    </a-table>

  </a-card>
</template>

<script>
import {onMounted, reactive, ref, toRefs, computed} from 'vue'
import {selectMerchant} from "../../../api";
import {
  fetchCollectionList,
  exportCollectionDetails,
  collectionBatchPushOrder,
  collectionPushOrder
} from "../../../api/transaction";
import i18n from "../../../locale";
import {merchantTransferExport} from "../../../api/capital";
import {export_json_to_excel} from "../../../utils/exportExcel";
import {message, Modal} from "ant-design-vue";
import {hasPermission} from "../../../utils/permiss";
import {formatMoney} from "../../../utils";

const $t = i18n.global.t
const statusList = [
  {value: 1, label: $t('未支付')},
  {value: 3, label: $t('成功')},
  {value: 5, label: $t('下单失败')},
]
const tableColumn = [
  {
    title: $t('交易流水'),
    dataIndex: 'transactionId',
    width: 150,
    align: 'center',
  },
  {title: $t('平台订单号'), dataIndex: 'platOrderId', width: 150, align: 'center'},
  {title: $t('商户订单号'), dataIndex: 'orderId', width: 150, align: 'center'},
  {title: $t('应用ID'), dataIndex: 'appId', width: 100, align: 'center'},
  {title: $t('客户姓名'), dataIndex: 'name', width: 100, align: 'center'},
  {title: $t('身份证号码'), dataIndex: 'idCard', width: 150, align: 'center'},
  {
    title: $t('还款类型'), dataIndex: 'transferType', width: 100, align: 'center', customRender: ({text}) => {
      return text === 0 ? 'clabe' : text === 1 ? 'OXXO' : ''
    }
  },
  {title: $t('收款账号'), dataIndex: 'vaNumber', width: 150, align: 'center'},
  {title: $t('银行名称'), dataIndex: 'bankName', width: 100, align: 'center'},
  {
    title: $t('实付金额'), dataIndex: 'amount', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('到账金额'), dataIndex: 'entryAmount', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('手续费'), dataIndex: 'fee', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('手续费扣除方式'), dataIndex: 'deductionType', width: 100, align: 'center', customRender: ({text}) => {
      return text === 1 ? $t('手续费另计') : $t('从金额中扣除')
    }
  },
  {title: $t('标识符'), dataIndex: 'identifier', width: 150, align: 'center'},
  {title: $t('创建时间'), dataIndex: 'createTime', width: 150, align: 'center'},
  {title: $t('完成时间'), dataIndex: 'endTime', width: 150, align: 'center'},
  {
    title: $t('状态'), dataIndex: 'status', width: 100, align: 'center', customRender: ({text}) => {
      const status = statusList.find(item => item.value === text)
      return status ? status.label : text
    }
  },
  {title: $t('描述'), dataIndex: 'statusDesc', width: 100, align: 'center',},
  {title: $t('操作'), width: 100, fixed: 'right', align: 'center', slots: {customRender: 'handle'}},
]
export default {
  name: "CollectionDetail",
  setup() {
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      tableLoading: false,
      merchantList: [],
      statusVisible: false,
      statusForm: {},
      exportLoading: false,
      selectedRowKeys: []
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + $t('条'),
      onChange: (value) => {
        state.page.pageNum = value
        methods.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        methods.getTableData()
      }
    }))
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: (value) => {
        state.selectedRowKeys = value
      }
    }))
    const methods = {
      async getTableData() {
        state.tableLoading = true
        const [createTimeStart, createTimeEnd] = state.page.createTime || []
        const [endTimeStart, endTimeEnd] = state.page.resolveTime || []
        const params = {
          ...state.page,
          createTimeStart, createTimeEnd, endTimeStart, endTimeEnd,
          createTime: undefined,
          resolveTime: undefined
        }
        const res = await fetchCollectionList(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
          state.tableLoading = false
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        methods.getTableData()
      },
      batchPush() {
        if (state.selectedRowKeys.length <= 0) return message.error($t('请勾选订单'))
        Modal.confirm({
          title: $t('确认推送') + '?',
          async onOk() {
            const res = await collectionBatchPushOrder(state.selectedRowKeys)
            if (res.code === 200) {
              message.success($t('操作成功'))
              methods.getTableData()
              state.selectedRowKeys = []
            }
          },
        });
      },
      push({platOrderId}) {
        Modal.confirm({
          title: $t('确认推送') + '?',
          async onOk() {
            const res = await collectionPushOrder({platOrderId})
            if (res.code === 200) {
              message.success($t('操作成功'))
              methods.getTableData()
            }
          },
        });
      },
      async exportExcel() {
        state.exportLoading = true
        const [createTimeStart, createTimeEnd] = state.page.createTime || []
        const [endTimeStart, endTimeEnd] = state.page.resolveTime || []
        const params = {
          ...state.page,
          createTimeStart, createTimeEnd, endTimeStart, endTimeEnd,
          createTime: undefined,
          resolveTime: undefined
        }
        const res = await exportCollectionDetails(params)
        if (res.code === 200) {
          const headerData = tableColumn.filter(item => item.title !== $t('操作'))
          const column = headerData.map(item => item.title)
          const filterVal = headerData.map(item => item.dataIndex)
          const list = [...res.data].map((item) => {
            item.status = statusList.find(_ => _.value === item.status).label
            item.transferType = item.transferType === 0 ? 'clabe' : item.transferType === 1 ? 'OXXO' : ''
            return item;
          }).map((v) => filterVal.map((j) => v[j]));
          const fileName = $t("收款明细");
          export_json_to_excel({
            header: column,
            data: list,
            filename: fileName,
          });
          state.exportLoading = false
        } else {
          state.exportLoading = false
        }
      }
    }
    onMounted(() => {
      selectMerchant().then(res => {
        state.merchantList = res
      })
      methods.getTableData()
    })
    return {
      pagination,
      statusList,
      rowSelection,
      tableColumn,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
